#!/usr/bin/env bash
# duokaiji.sh - 引导脚本：下载/更新菜单与功能模块到当前目录并执行菜单
# 用法：
#   bash duokaiji.sh
#   bash duokaiji.sh --base https://node.daytool.cn/node/sh/
#   DUOKAIJI_BASE=https://node.daytool.cn/node/sh/ bash duokaiji.sh

set -euo pipefail

# ========= 可配置项 =========
DEFAULT_BASE="https://node.daytool.cn/node/sh"
BASE_URL="${DUOKAIJI_BASE:-$DEFAULT_BASE}"

# 可通过 --base 覆盖
if [[ "${1:-}" == "--base" && -n "${2:-}" ]]; then
  BASE_URL="${2%/}"
  shift 2
fi

# 需要下载的文件清单
ROOT_FILES=( "menu.sh" "VERSION" )
ACTION_DIR="actions"
ACTION_FILES=(
  "_common.sh"
  "mirrors.sh"
  "sysupdate.sh"
  "install_basic.sh"
  "install_net.sh"
  "install_dev.sh"
  "install_nginx.sh"
  "install_node.sh"
  "install_docker.sh"
  "install_ssh_fw.sh"
  "xui_3xui.sh"
  "install_gost.sh" 
  "net_tools.sh"
  "optimize.sh"
  "dns_tools.sh"
)

# ========= 颜色与日志 =========
GREEN="\033[1;32m"; YELLOW="\033[1;33m"; RED="\033[1;31m"; BLUE="\033[1;34m"; RESET="\033[0m"
log_info()  { echo -e "${GREEN}[INFO]${RESET} $*"; }
log_warn()  { echo -e "${YELLOW}[WARN]${RESET} $*"; }
log_error() { echo -e "${RED}[ERR ]${RESET} $*" >&2; }

# ========= 下载工具 =========
have_cmd() { command -v "$1" >/dev/null 2>&1; }

fetch() {
  # fetch <remote_url> <local_path>
  local url="$1" dst="$2"
  if have_cmd curl; then
    curl -fsSL --connect-timeout 10 --retry 3 --retry-delay 1 "$url" -o "$dst"
  elif have_cmd wget; then
    wget -q --timeout=10 --tries=3 "$url" -O "$dst"
  else
    log_error "缺少下载工具（curl 或 wget）。请先安装：apt update && apt install -y curl"
    return 1
  fi
}

# ========= 主流程 =========
echo -e "${BLUE}==> 双开鸡引导器：下载菜单与功能模块${RESET}"
log_info "远程仓库：$BASE_URL"
mkdir -p "./$ACTION_DIR"

# 先试着拉取 VERSION（可选）
REMOTE_VERSION="unknown"
TMP_VER=".VERSION.tmp.$$"
if fetch "$BASE_URL/VERSION" "$TMP_VER"; then
  REMOTE_VERSION="$(tr -d '\r\n' < "$TMP_VER" || true)"
  rm -f "$TMP_VER"
  log_info "远程版本：$REMOTE_VERSION"
else
  log_warn "未获取到远程 VERSION（忽略）。"
fi

# 下载根文件
for f in "${ROOT_FILES[@]}"; do
  url="$BASE_URL/$f"
  dst="./$f"
  log_info "下载：$f"
  if ! fetch "$url" "$dst"; then
    log_warn "下载失败：$url"
  fi
done

# 下载 actions 模块
for f in "${ACTION_FILES[@]}"; do
  url="$BASE_URL/$ACTION_DIR/$f"
  dst="./$ACTION_DIR/$f"
  log_info "下载：actions/$f"
  if ! fetch "$url" "$dst"; then
    log_warn "下载失败：$url"
  fi
done

# 基础检查：必须有 menu.sh
if [[ ! -s "./menu.sh" ]]; then
  log_error "menu.sh 不存在或为空，无法继续。请检查远程路径：$BASE_URL"
  exit 2
fi

# 赋权并执行
chmod +x ./menu.sh || true
log_info "下载完成，启动菜单（menu.sh）..."
exec bash ./menu.sh
